#!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''
@Project ：图灵学习 
@File    ：5.读取bilibili美女视频数据信息并存储csv.py
@IDE     ：PyCharm 
@Author  ：ChenLiGao
@Date    ：2024-11-29 10:46
'''
import csv
import time

import requests
headers = {
    'cookie': 'b_lsid=66B8FEE5_19375CA3273; _uuid=714D616D-3B65-E28D-AB56-10AE110ACCD17C05755infoc; buvid_fp=6a4b33158bcd7d048bed805765c1f8cb; buvid3=F49E57FA-6760-5DF9-A3E4-DF368A1A8A1588247infoc; b_nut=1732848017; buvid4=CC26DC7A-6342-6766-8D3A-6B4F803F87C188247-024112902-W4oktAkiHm9CCCNc154PYQ%3D%3D; bili_ticket=eyJhbGciOiJIUzI1NiIsImtpZCI6InMwMyIsInR5cCI6IkpXVCJ9.eyJleHAiOjE3MzMxMDcxOTEsImlhdCI6MTczMjg0NzkzMSwicGx0IjotMX0.SB1_eZ5sFo1uqDvbvLksnQ-vF68vCQUabaLWg5aGTfw; bili_ticket_expires=1733107131; CURRENT_FNVAL=4048; sid=pq7ounan',
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36',
}

url = 'https://api.bilibili.com/x/web-interface/wbi/search/type'

params = {
    'category_id': '',
    'search_type': 'video',
    'ad_resource': '5654',
    '__refresh__': 'true',
    '_extra': '',
    'context': '',
    'page': 2,
    'page_size': '42',
    'pubtime_begin_s': '0',
    'pubtime_end_s': '0',
    'from_source': '',
    'from_spmid': '333.337',
    'platform': 'pc',
    'highlight': '1',
    'single_column': '0',
    'keyword': '美女',
    'qv_id': 'HKs3UUguuKyDx8WOnwgMoZnbue15IdVe',
    'source_tag': '3',
    'gaia_vtoken': '',
    'dynamic_offset': '36',
    'web_location': '1430654',
    'w_rid': '6f1c07b89f401b65f18ed10dc9604e9a',
    'wts': '1732849376',
}
def save_bilibili_csv(url):
    response = requests.get(url,
                            headers=headers,
                            params=params
                            ).json()
    with open('5bilibili.csv', 'w', encoding='utf-8', newline='')as f:
        field_list = ['author', 'arcurl', 'tag']
        # 创建写入对象
        fcsv = csv.DictWriter(f, fieldnames=field_list)
        # 写入表头
        fcsv.writeheader()

        for result in response['data']['result']:
            item = dict()
            item['author'] = result.get("author")
            item['arcurl'] = result.get("arcurl")
            item['tag'] = result.get("tag")
            fcsv.writerow(item)

save_bilibili_csv(url)
